package com.by.controller;

import com.by.common.controller.BaseController;
import com.by.common.entity.ResultBean;
import com.by.common.group.ISave;
import com.by.common.group.IUpdate;
import com.by.entity.Dept;
import com.by.query.DeptQuery;
import com.by.service.DeptService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "部门管理")
@RestController
@RequestMapping("/v1")
public class DeptController extends BaseController {
    @Autowired
    DeptService deptService;

    /*
    * 新增部门
    * */
    @PostMapping("/dept")
    @ApiOperation("新增部门")
    public ResultBean addDept(@Validated(ISave.class) @RequestBody Dept dept, BindingResult result) {
        validate(result);
        System.out.println(dept);
        //查询是否存在该部门
        String n= deptService.queryByName(dept.getName());
        if(n != null){//存在则不能创建
            return fail("该部门已存在!");
        }

        int r= deptService.save(dept);
        return saveResult(r);
    }
    /*
    * 修改
    * */
    @ApiOperation("修改部门")
    @PutMapping("/dept")
    public ResultBean update(@Validated(IUpdate.class) @RequestBody Dept dept, BindingResult result) {
        validate(result);
        int r= deptService.update(dept);
        return saveResult(r);
    }


    /*
    * 删除部门
    * */
    @ApiImplicitParam(name = "id",value = "部门id",dataTypeClass = Integer.class,required = true,paramType = "query")
    @ApiOperation("删除部门")
    @DeleteMapping("/dept")
    public ResultBean delete(@RequestParam(name = "id",required = true,defaultValue = "0") int id){
        int rs= deptService.delete(id);
        if (rs==2){
            return fail("该部门下有子部门不能删除");
        }
        return saveResult(rs);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "部门id",dataTypeClass = Integer.class ,required = true,paramType = "query"),
            @ApiImplicitParam(name="status",value = "部门状态 0 禁用 1 启用",dataTypeClass = Integer.class ,required = true,paramType = "query")
    })
    @ApiOperation("修改部门状态")
    @PutMapping("/dept/status")
    public ResultBean updateStatus(@RequestParam(name = "id",required = true) int id,@RequestParam(name="status",required = true,defaultValue = "0") int status) {
        int r= deptService.updateStatus(id,status);
        return updateResult(r);
    }
    /*
    * 查询
    * */
    @ApiOperation("查询部门")
    @PostMapping("/dept/query")
    public ResultBean query(@RequestBody DeptQuery deptQuery){
        List list = deptService.queryChildDept(deptQuery);
        return success("部门列表",list);
    }
    /*
    * 查询部门树
    * */
    @ApiOperation("查询部门树")
    @GetMapping("/dept/queryTree")
    public ResultBean queryTree(){
        List list = deptService.queryTree(0);
        return success("部门树",list);
    }

}
